<template>
    <div style="width:100%; height: 100vh;background-color: #2a5caa;overflow: hidden;">
        <div style="width:400px; margin:150px auto;">
   、         <div style="color: #cccccc; font-size: 30px; text-align: center;margin-bottom: 20px;">
                用户登录
            </div>
            <el-form ref="formLogin" :model="formLogin" :rules="formRules" class="demo-form-inline">
                <el-form-item prop="userName">
                    <el-input prefix-icon="Avatar" v-model="formLogin.userName" placeholder="用户名">
                    </el-input>
                </el-form-item>

                <el-form-item prop="password">
                    <el-input  prefix-icon="Key" v-model="formLogin.password"
                               show-password="true" placeholder="密 码"></el-input>
                </el-form-item>
                <el-checkbox v-model="checked">记住密码</el-checkbox>
                <el-link type="primary" style="position:relative;left:65%">忘记密码</el-link>
                <el-form-item>
                    <el-button type="primary"  @click="handleSubmit"  style="width: 100%;">登录</el-button>
                </el-form-item>
                    <el-link type="primary" style="position:relative;left:90%" @click="toRegister()">注册</el-link>
            </el-form>
        </div>
    </div>
</template>

<script>
    import { Avatar } from "@element-plus/icons";
    import { Key } from "@element-plus/icons";
    import request from "../../utils/request";
    import CryptoJS from 'crypto-js'
    import {ElMessage} from "element-plus"; //加密js
    import { getToken, setToken, removeToken } from '@/utils/auth';

    export default{
        name:'Login',
        components: {
            Avatar,
            Key
        },
        data(){
            return{
                formRules:{
                    userName:'',
                    password:'',
                },
                formLogin:{},
                formRules:{
                    userName:[
                        {required:true,message:"用户名不能为空",trigger:"blur"}
                    ],
                    password:[
                        {required:true,message:"密码不能为空",trigger:"blur"}
                    ]
                },
                checked: false //是否选中记住密码 true为选中
            }
        },
        created(){
            // 判断是否记住密码
            if(localStorage.getItem("rememberPsw") == 'true'){
                this.checked=true;
                this.getCookie()
            }
        },
        methods:{
            //登录方法
            handleSubmit() {
                var that = this;
                let loginParams = {
                    userName: this.formLogin.userName, //获取账号
                    password: this.formLogin.password //获取密码
                };
                if (that.checked == true) {
                    //传入账号，密码，保存天数
                    that.setCookie(that.formLogin.userName, that.formLogin.password, 1);
                    localStorage.setItem("rememberPsw",'true');
                } else {
                    //清空Cookie
                    that.clearCookie();
                }
                localStorage.setItem("rememberPsw", that.checked);
                // //登录请求
                request.post("/api/user/sys/doLogin",loginParams).then(resp=>{
                    if(resp.status =="M0200"){
                        const data={"token":resp.data.token};
                        setToken(data.token);
                        sessionStorage.setItem("user",JSON.stringify(resp.data.user));
                        this.$router.push("/")
                    }else{
                        //提示
                        ElMessage({
                            message:resp.msg,
                            type:"error"

                        })
                        this.$router.push("/login")
                    }
                })
            },

            //设置cookie方法
            setCookie(userName, password, days) {
                var text = CryptoJS.AES.encrypt(password, 'secret key 123');//使用CryptoJS方法加密
                var saveDays = new Date(); //获取时间
                saveDays.setTime(saveDays.getTime() + 24 * 60 * 60 * 1000 * days); //保存的天数
                //字符串拼接存入cookie
                window.document.cookie = "userName" + "=" + userName + ";path=/;expires=" + saveDays.toGMTString();
                window.document.cookie = "password" + "=" + text + ";path=/;expires=" + saveDays.toGMTString();
            },

            //读取cookie
            getCookie() {
                if (document.cookie.length > 0) {
                    var arr = document.cookie.split('; '); //这里显示的格式需要切割一下自己可输出看下
                    for (var i = 0; i < arr.length; i++) {
                        var arr2 = arr[i].split('='); //再次切割
                        //这里会切割出以mobile为第0项的数组、以password为第0项的数组，判断查找相对应的值
                        if (arr2[0] == 'userName') {
                            this.formLogin.userName = arr2[1]; //拿到账号
                        } else if (arr2[0] == 'password') {
                            //拿到拿到加密后的密码arr2[1]并解密
                            var bytes = CryptoJS.AES.decrypt(arr2[1].toString(), 'secret key 123');
                            var plaintext = bytes.toString(CryptoJS.enc.Utf8); //拿到解密后的密码（登录时输入的密码）
                            this.formLogin.password = plaintext;
                        }
                    }
                }
            },
            //清除cookie
            clearCookie() {
                this.setCookie("", "", 0); //账号密码置空，天数置0
            },
            toRegister(){
                this.$router.push('/register');
            }
        }

    }
</script>
